<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="css/index.css">
    <script src="js/jquery-1.12.4.min.js"></script>
    <script src="js/template-native.js"></script>
    <script id="tem" type="text/html">
        <% for (var i = 0 ; i < comments.length ; i++) { %>
            <li uid = "<%=comments[i].id%>">
              <p class="floor"><%=comments[i].id%><a href="javascript:;" class="delete">删除</a></p>
              <p class="author">层主：<span class="name"><%=comments[i].username%></span></p>
              <p class="content"><%=comments[i].content%></p>
            </li>
        <% } %>
    </script>
</head>

<body>
    <div class="main">
        <div class="post">
          <h2>z</h2>
          <p class="author">楼主：z</p>
          <p class="txt">z</p>
        </div>
        <div class="reply">
          <h4>发表回复</h4>
          <p>用户名：<input type="text" class="user"></p>
          <textarea class="editor"></textarea>
          <input type="button" value="发表" class="btn">
        </div>
        <div class="cmts">
          <ul class="list">

          </ul>
        </div>
      </div>
</body>
<script>
  const $lis = $(".list");
    $.ajax({
        url: "http://localhost:3000/db",
        type: "GET",
        success: function (data) {
            $lis.html(template("tem",data));
            deletedata();
        }
    });
    $(".reply .btn").click(function () {
      const $user = $(".reply .user").val();
      const $editor = $(".reply .editor").val();
      $.ajax({
        url: "http://localhost:3000/comments",
        type: "POST",
        datatype: "json",
        data: {username: $user , content: $editor},
        success: function (data) {
          $lis.append(template("tem",{"comments": [data]}));
          deletedata();  
        }
      })
      $(".reply .user").val("");
      $(".reply .editor").val("");
    });
    function deletedata () {
      $(".delete").click(function () {
        const $li = $(this).parents("li");
        const $index = $li.attr("uid");
        console.log($index);
        $.ajax({
          url: "http://localhost:3000/comments/"+ $index,
          type: "delete"
        })
        $li.remove();
      });
    }
</script>
</html>